#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:39
# file: security.py
# author: lotus163
from datetime import timedelta, datetime
from typing import Optional

from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from passlib.context import CryptContext

from backend.config.setting import settings

# 密码加密算法
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

get_token = OAuth2PasswordBearer(tokenUrl=f"{settings.API_PREFIX}/token")


def hash_password(password: str) -> str:
    """密码加密"""
    return pwd_context.hash(password)


def verify_password(plain_password, hashed_password) -> bool:
    """验证密码"""
    return pwd_context.verify(plain_password, hashed_password)


def get_expires()->datetime:
    """获取过期时间"""
    return datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)


def create_access_token(data: dict, expires: Optional[datetime] = None) -> str:
    """
    生成token
    :param expires: 过期时间
    :param data: 存储数据
    :param expires_delta: 有效时间
    :return: 加密后的token
    """
    to_encode = data.copy()
    if not expires:
        expires = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expires})  # eg: {'sub': '1', scopes: ['items'] 'exp': '123'}
    return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
